package BookStore.EBook.ConvertorForAndroid;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

public class Convertor {
	
	private static String EXT_NAME = ".txt";
	private String mDBServer;
	private String mDBName;
	private boolean mIsIntegratedSecurity;
	private String mUserName;
	private String mPassword;
	private static String SEPARATOR = ":";
	
	public Convertor(String DBServer, String DBName, boolean isIntegratedSecurity, String userName, String password)
	{
		mDBServer = DBServer;
		mDBName = DBName;
		mIsIntegratedSecurity = isIntegratedSecurity;
		mUserName = userName;
		mPassword = password;
	}
	
	
	public void ConvertFromLocalRepo(String bkName, String pathSrc, String pathDes)
	{
		File fromPath = new File(pathSrc);
		if (!fromPath.exists() || !fromPath.isDirectory()) {
			System.out.println(fromPath.getAbsolutePath()+" doesn't exist!");
			return;
		}
		
		File toPath = new File(pathDes);
		if (!toPath.exists()) {
			toPath.mkdirs();
		}
		
		List<String> chapters = ChapterSorter.getOrderedChapterNamesFromDB(bkName, mDBServer, mDBName, mUserName, mPassword, mIsIntegratedSecurity);
		if(chapters==null || chapters.isEmpty())
		{
			System.out.println(bkName+" cannot find in database!");
			return;
		}
		
		HashMap<String, String> hm = new HashMap<String, String>();
		
		
		for(int i = 0; i < chapters.size(); i++)
		{
			String chapter=chapters.get(i);
			File sourceFile = new File(fromPath.getAbsolutePath()+ File.separator + chapter + File.separator + chapter + ".txt");
			if(!sourceFile.exists())
			{
				System.out.println("Book " + bkName +": Chapter " + chapter + " cannot find in local repo!");
				continue;
			}
			
			String newName = "chapter" + i;
			hm.put(chapter, newName);
			
			File targetFile = new File(toPath.getAbsolutePath() + File.separator + newName);
            try {
				FileUtil.copyFile(sourceFile, targetFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
//		File[] files = fromPath.listFiles();
//        for (int i = 0; i < files.length; i++) {
//            if (files[i].isFile()) {
//                File sourceFile = files[i];
//                String srcName = sourceFile.getName();
//                if(srcName.endsWith(".txt"))srcName = srcName.substring(0, srcName.length()-4);
//                String newName = "chapter" + i;
//                hm.put(srcName, newName);
//                File targetFile = new File(toPath.getAbsolutePath() + File.separator + newName);
//                try {
//					FileUtil.copyFile(sourceFile, targetFile);
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//            }
//            
//            if (files[i].isDirectory()) {
//
//            	File sourceFile = new File(files[i].getAbsolutePath() + File.separator + files[i].getName() + EXT_NAME);
//            	if(!sourceFile.exists())continue;
//                String srcName = sourceFile.getName();
//                if(srcName.endsWith(".txt"))srcName = srcName.substring(0, srcName.length()-4);
//                String newName = "chapter" + i;
//                hm.put(srcName, newName);
//                File targetFile = new File(toPath.getAbsolutePath() + File.separator + newName);
//                try {
//					FileUtil.copyFile(sourceFile, targetFile);
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//            }
//            
//        }
        
        // Create the index file, the format is:
        // [Book Name]
        // [Origianl Name of Chapter 1] SEPARATOR [Raw Source ID in Android]
        // [Origianl Name of Chapter 2] SEPARATOR [Raw Source ID in Android]
        // ...
        String bookName = fromPath.getName();
        String indexFileName = toPath.getAbsolutePath() + File.separator + "index";
        
        try{
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(indexFileName),"UTF-8");
            out.write(bkName+"\n");
            
            for(int i = 0; i < chapters.size(); i++)
            {
            	if(hm.containsKey(chapters.get(i)))
            		out.write(chapters.get(i) + SEPARATOR + hm.get(chapters.get(i)) + "\n");
            }
            out.flush();
            out.close();
        }catch(Exception ex)
        {
        	ex.printStackTrace();
        }
	}
	
	public void ConvertFromDB(String bookID, String pathDes)
	{
		File toPath = new File(pathDes);
		if (!toPath.exists()) {
			toPath.mkdirs();
		}
		
		Connection con = DBConnection.getConnection(mDBServer, mDBName, mIsIntegratedSecurity, mUserName, mPassword);
		HashMap<String, String> hm = new HashMap<String, String>();
		List<String> chapters = new ArrayList<String>();
		
		Statement stmt;
		try {
			stmt = con.createStatement();
			String sql = "Select ChapterName, ChapterContent FROM t_chapter where BookId='" + bookID + "' order by Created";
	        ResultSet rs=stmt.executeQuery(sql);

	        int i =0;
	        
	        while(rs.next()){
	        	
	        	String chapter=rs.getString("ChapterName");
				String content=rs.getString("ChapterContent");
				if(chapter==null || content==null)
				{
					System.out.println("Book " + bookID +": Chapter " + chapter + " cannot find in DB!");
					continue;
				}
				chapters.add(chapter);
				String newName = "chapter" + i;
				hm.put(chapter, newName);
				i++;
				
				File targetFile = new File(toPath.getAbsolutePath() + File.separator + newName);
	            try {
					FileUtil.writeStringToFile(content, targetFile);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
	        }
	        stmt.close();
			con.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        String indexFileName = toPath.getAbsolutePath() + File.separator + "index";
        String bkName = getBookNameFromId(bookID);
        try{
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(indexFileName),"UTF-8");
            out.write(bkName+"\n");
            
            for(int i = 0; i < chapters.size(); i++)
            {
            	if(hm.containsKey(chapters.get(i)))
            		out.write(chapters.get(i) + SEPARATOR + hm.get(chapters.get(i)) + "\n");
            }
            out.flush();
            out.close();
        }catch(Exception ex)
        {
        	ex.printStackTrace();
        }
        
	}
	
	public void ConvertAllFromDB(String pathDes)
	{
		File toPath = new File(pathDes);
		if (!toPath.exists()) {
			toPath.mkdirs();
		}
		
		Connection con = DBConnection.getConnection(mDBServer, mDBName, mIsIntegratedSecurity, mUserName, mPassword);
		HashMap<String, String> hm = new HashMap<String, String>();
		List<String> chapters = new ArrayList<String>();
		
		Statement stmt;
		try {
			stmt = con.createStatement();
			String sql = "Select BookId, BookCategory, BookName FROM t_book";
	        ResultSet rs=stmt.executeQuery(sql);

	        int i =0;
	        
	        while(rs.next()){
	        	
	        	String bookId = rs.getString("BookId");
	        	String bookName = rs.getString("BookName");
	        	String bookCategory = rs.getString("BookCategory");
	        	if(bookId!=null)
	        	{
	        		String path = pathDes + File.separator + bookCategory + File.separator + bookName;
	        		
	        		writeBookIdToFile(path + File.separator + bookId);
	        		
	        		//ConvertFromDB(bookId, path + File.separator + "raw");
	        	}
	        }
	        stmt.close();
			con.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void writeBookIdToFile(String path)
	{
		File toPath = new File(path);
		if (!toPath.exists()) {
			try {
				toPath.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	
	private String getBookNameFromId(String bookId)
	{
		Connection con = DBConnection.getConnection(mDBServer, mDBName, mIsIntegratedSecurity, mUserName, mPassword);

		Statement stmt;
		String bookName="";
		try {
			stmt = con.createStatement();
			String sql = "Select BookName FROM t_book where BookId='" + bookId + "'";
	        ResultSet rs=stmt.executeQuery(sql);

	        while(rs.next()){
	        	bookName = rs.getString("BookName");
	        }
	        stmt.close();
			con.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return bookName;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String bookRepo = "G:\\BookStore\\燃文";
		String androidBookRepo = "G:\\BookStore\\EbookForAndroid";
		
		File root = new File(bookRepo);
		if (!root.exists() || !root.isDirectory()) {
			System.out.println(root.getAbsolutePath()+" is not the book repo!");
			return;
		}
		
		File androidRoot = new File(androidBookRepo);
		String server = "localhost:1433";
		String dbName = "EB";
		String user = "ads\\limin";
		String password = "Bright19";
		boolean isIntegratedSecurity = true;

		Convertor convertor = new Convertor(server, dbName, isIntegratedSecurity, user, password);
		
		convertor.ConvertAllFromDB(androidBookRepo);
		
		
//		File[] books = root.listFiles();
//		for (int i = 0; i < books.length; i++)
//		{
//			if (books[i].isDirectory()) 
//			{
//				String bookName = books[i].getName();
//				convertor.ConvertFromLocalRepo(bookName, root.getAbsolutePath()+ File.separator + bookName, androidRoot.getAbsolutePath()+ File.separator +bookName);
//			}
//		}
		

	}

}
